﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Utilities.Xml;

namespace EnglishStudy.ViewModel
{
   public class CommonViewModel
    {
       public async Task<string> GetLocation(string latitute,string longtitute)
       {
            string urlService = "http://maps.google.com/maps/api/geocode/xml?latlng="+latitute+","+longtitute+"&sensor=false";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(urlService);
            httpWebRequest.Method = "GET";


            var factory = new TaskFactory();
            var task = factory.FromAsync<WebResponse>(httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, null);
            try
            {

                var response = await task;
                HttpWebResponse st = (HttpWebResponse)response;
                GeocodeRes myObject = new GeocodeRes();
                using (var reader = new System.IO.StreamReader(st.GetResponseStream()))
                {
                    var getData =await ModelCreator<GeocodeRes>.CreateInstanceFromXmlAsync(reader.ReadToEnd().ToString(),"");
                    for(int i = 0; i < getData.resultList[0].AddressComponentList.Count; i++)
                    {
                        if (getData.resultList[0].AddressComponentList[i].Type[0] == "country")
                            return getData.resultList[0].AddressComponentList[i].ShortName;
                    
                    }
                    return "";
                }
                
            }
            catch (Exception e)
            {

            }
            finally
            {
                ////Logger.LogVerbose("Finally!");
            }
            return "";
       }
    }
    [XmlRoot(ElementName = "GeocodeResponse")]
    public class GeocodeRes
    {
        public GeocodeRes()
        {
            resultList = new List<Result>();
        }
        [XmlElement(ElementName = "result")]
        public List<Result> resultList { get; set; }
    }

    public class Result
    {
        public Result()
        {
            AddressComponentList = new List<AddressComponent>();
        }

        [XmlElement(ElementName = "address_component")]
        public List<AddressComponent> AddressComponentList { get; set; }
    }
    public class AddressComponent
    {
        public AddressComponent()
        {
            Type = new List<string>();
        }

        [XmlElement(ElementName = "long_name")]
        public string LongName { get; set; }

        [XmlElement(ElementName = "short_name")]
        public string ShortName { get; set; }

        [XmlElement(ElementName = "type")]
        public List<string> Type { get; set; }

    }
}
